import time
import json
from flask import render_template, request, redirect, url_for, Response
from . import front
from Search.search import base_search
from Search.getdata import *

@front.route('/search')
def _result_page():
    t = time.perf_counter() 
    keywords = request.args.get('keywords')
    if request.cookies.get('search_history'):
        search_history: list = json.loads(request.cookies.get('search_history'))  
    else:
        search_history = []

    if not keywords:
        return redirect(url_for('front._index'))  
    else:
        try:
            result_list = base_search(keywords, search_history)
            results = []
            for result in result_list:
                url = result[0]
                temp_series = information.loc[url].fillna('')
                title = temp_series['title'].replace('_', '/')
                description = temp_series['description']
                cos_sim_score = result[1]
                page_rank_score = page_rank.loc[url]['page_rank']
                # 假设文件存储在外部服务器上，使用正确的域名和协议
                file_url = url  # 修改这里
                results.append((title, file_url, description, cos_sim_score * page_rank_score))
            
            results.sort(key=lambda x: x[3], reverse=True)
        except KeyError :
            cost_time = f'{time.perf_counter() - t: .2f}'
            return render_template(r'no_result.html', keywords=keywords, cost_time=cost_time)
        cost_time = f'{time.perf_counter() - t: .2f}'

    resp = Response(render_template(r'result_web_pages.html', keywords=keywords, results=results, len_results=len(results), cost_time=cost_time, search_history=search_history))

    if keywords not in search_history:
        search_history.append(keywords) 
    if len(search_history) > 10:
        search_history.pop(0) 

    resp.set_cookie('search_history', json.dumps(search_history), max_age=60 * 60 * 24 * 30)  # 设置cookie时间
    return resp